---
title: 常见问题排查
description: CActor框架常见问题的诊断和解决方案
category: 故障排除
order: 1
tags: [故障排除, 调试, 问题解决, 诊断]
author: CActor团队
publishedAt: 2024-01-15
updatedAt: 2024-01-15
difficulty: intermediate
---

# 常见问题排查

本文档收集了CActor框架使用过程中的常见问题及其解决方案。

## 系统启动问题

### 问题1：ActorSystem创建失败

**症状：**

```
Exception in thread "main" cactor.system.ActorSystemCreationException:
Failed to create actor system: Configuration error
```

**可能原因：**

- 配置文件格式错误
- 端口被占用
- 内存不足
- 权限问题

**解决方案：**

```cangjie
// 1. 检查配置文件
try {
    let config = ConfigFactory.load("application.conf")
    let system = ActorSystem.create("MySystem", config)
} catch (e: ConfigException) {
    logger.error("Configuration error: ${e.message}")
    // 检查配置文件语法
}

// 2. 检查端口占用
func checkPortAvailable(port: Int32): Bool {
    try {
        let socket = ServerSocket(port)
        socket.close()
        return true
    } catch (e: IOException) {
        return false
    }
}

// 3. 检查内存
func checkMemory(): Unit {
    let runtime = Runtime.getRuntime()
    let maxMemory = runtime.maxMemory()
    let totalMemory = runtime.totalMemory()
    let freeMemory = runtime.freeMemory()

    logger.info("Max memory: ${maxMemory / 1024 / 1024}MB")
    logger.info("Total memory: ${totalMemory / 1024 / 1024}MB")
    logger.info("Free memory: ${freeMemory / 1024 / 1024}MB")
}
```

### 问题2：Actor创建失败

**症状：**

```
cactor.actor.ActorCreationException: Failed to create actor 'myActor'
```

**解决方案：**

```cangjie
// 检查Actor类定义
class MyActor : Actor {
    // 确保有无参构造函数
    init() {
        // 初始化代码
    }

    override func receive(message: Message): Unit {
        // 消息处理逻辑
    }
}

// 正确的Actor创建方式
try {
    let actorRef = system.actorOf<MyActor>("myActor")
    logger.info("Actor created successfully: ${actorRef.path}")
} catch (e: ActorCreationException) {
    logger.error("Failed to create actor: ${e.message}")
    // 检查Actor类是否正确实现
}
```

## 消息传递问题

### 问题3：消息丢失

**症状：**

- 发送的消息没有被处理
- Actor没有收到预期的消息

**诊断步骤：**

```cangjie
class DiagnosticActor : Actor {
    var messageCount: Int64 = 0

    override func receive(message: Message): Unit {
        messageCount += 1
        logger.debug("Received message #${messageCount}: ${message}")

        match (message) {
            case TestMessage(id) => {
                logger.info("Processing test message: ${id}")
                // 确认消息处理
                sender.send(AckMessage(id))
            }
            case _ => {
                logger.warn("Unknown message type: ${message.getClass().getName()}")
            }
        }
    }
}

// 消息发送确认
class MessageSender {
    func sendWithConfirmation(actor: ActorRef, message: Message): Future<Bool> {
        let promise = Promise<Bool>()

        // 设置超时
        let timeout = system.scheduler().scheduleOnce(
            delay: 5.seconds,
            runnable: {
                promise.failure(TimeoutException("Message send timeout"))
            }
        )

        // 发送消息并等待确认
        actor.ask<AckMessage>(message).onComplete { result =>
            timeout.cancel()
            match (result) {
                case Success(ack) => promise.success(true)
                case Failure(e) => promise.failure(e)
            }
        }

        return promise.future
    }
}
```

### 问题4：消息积压

**症状：**

- 系统响应变慢
- 内存使用持续增长
- Actor邮箱队列过长

**诊断和解决：**

```cangjie
class BackpressureActor : Actor {
    let maxQueueSize: Int32 = 1000
    var currentQueueSize: Int32 = 0
    let processingTime: Histogram = Metrics.histogram("processing.time")

    override func receive(message: Message): Unit {
        let startTime = System.nanoTime()

        match (message) {
            case WorkMessage(data) => {
                // 检查队列大小
                if (currentQueueSize >= maxQueueSize) {
                    logger.warn("Queue full, dropping message")
                    sender.send(BackpressureMessage("Queue full"))
                    return
                }

                currentQueueSize += 1
                try {
                    processWork(data)
                } finally {
                    currentQueueSize -= 1
                    let processingTimeNs = System.nanoTime() - startTime
                    processingTime.update(processingTimeNs)
                }
            }
            case GetQueueSizeMessage() => {
                sender.send(QueueSizeResponse(currentQueueSize))
            }
        }
    }
}

// 监控邮箱大小
class MailboxMonitor {
    func checkMailboxSizes(system: ActorSystem): Unit {
        let stats = system.getMailboxStats()

        stats.forEach { (actorPath, mailboxSize) =>
            if (mailboxSize > 1000) {
                logger.warn("Large mailbox detected: ${actorPath} has ${mailboxSize} messages")
            }
        }
    }
}
```

## 性能问题

### 问题5：高延迟

**诊断工具：**

```cangjie
class LatencyTracker {
    let latencyHistogram: Histogram = Metrics.histogram("message.latency")

    func trackMessageLatency(actor: ActorRef, message: Message): Unit {
        let startTime = System.nanoTime()

        actor.ask<Any>(message).onComplete { _ =>
            let latency = System.nanoTime() - startTime
            latencyHistogram.update(latency)

            if (latency > 10_000_000) { // 10ms
                logger.warn("High latency detected: ${latency / 1_000_000}ms for ${message}")
            }
        }
    }

    func getLatencyStats(): LatencyStats {
        let snapshot = latencyHistogram.getSnapshot()
        return LatencyStats(
            mean: snapshot.getMean() / 1_000_000, // 转换为毫秒
            p50: snapshot.getMedian() / 1_000_000,
            p95: snapshot.get95thPercentile() / 1_000_000,
            p99: snapshot.get99thPercentile() / 1_000_000
        )
    }
}
```

### 问题6：内存泄漏

**检测和修复：**

```cangjie
class MemoryLeakDetector {
    let actorMemoryUsage: Map<String, Long> = Map()

    func checkForLeaks(): Unit {
        let runtime = Runtime.getRuntime()
        let usedMemory = runtime.totalMemory() - runtime.freeMemory()

        // 检查内存增长趋势
        if (isMemoryGrowthAbnormal(usedMemory)) {
            logger.warn("Potential memory leak detected")
            dumpHeap()
            analyzeActorMemoryUsage()
        }
    }

    func analyzeActorMemoryUsage(): Unit {
        // 分析各个Actor的内存使用
        let actorStats = getActorMemoryStats()

        actorStats.forEach { (actorPath, memoryUsage) =>
            if (memoryUsage > 100 * 1024 * 1024) { // 100MB
                logger.warn("Actor ${actorPath} using excessive memory: ${memoryUsage / 1024 / 1024}MB")
            }
        }
    }
}

// 修复内存泄漏的Actor示例
class FixedActor : Actor {
    // 使用弱引用避免循环引用
    let cache: WeakHashMap<String, CachedData> = WeakHashMap()

    // 定期清理
    override func preStart(): Unit {
        context.system.scheduler().schedule(
            initialDelay: 1.minute,
            interval: 5.minutes,
            runnable: { cleanup() }
        )
    }

    func cleanup(): Unit {
        let now = System.currentTimeMillis()
        cache.entrySet().removeIf { entry =>
            (now - entry.getValue().timestamp) > 10.minutes.toMillis()
        }
    }
}
```

## 网络问题

### 问题7：连接超时

**症状：**

```
java.net.SocketTimeoutException: Connect timed out
```

**解决方案：**

```cangjie
class NetworkDiagnostics {
    func testConnectivity(host: String, port: Int32): ConnectivityResult {
        try {
            let startTime = System.currentTimeMillis()
            let socket = Socket()
            socket.connect(InetSocketAddress(host, port), 5000) // 5秒超时
            let connectTime = System.currentTimeMillis() - startTime
            socket.close()

            return ConnectivityResult(
                success: true,
                connectTime: connectTime,
                message: "Connection successful"
            )
        } catch (e: SocketTimeoutException) {
            return ConnectivityResult(
                success: false,
                connectTime: -1,
                message: "Connection timeout: ${e.message}"
            )
        } catch (e: IOException) {
            return ConnectivityResult(
                success: false,
                connectTime: -1,
                message: "Connection failed: ${e.message}"
            )
        }
    }

    func diagnoseNetworkIssues(remoteAddress: String): Unit {
        // 1. 检查DNS解析
        try {
            let address = InetAddress.getByName(remoteAddress)
            logger.info("DNS resolution successful: ${address.getHostAddress()}")
        } catch (e: UnknownHostException) {
            logger.error("DNS resolution failed: ${e.message}")
            return
        }

        // 2. 检查网络连通性
        let result = testConnectivity(remoteAddress, 8080)
        if (!result.success) {
            logger.error("Network connectivity issue: ${result.message}")
        }

        // 3. 检查防火墙
        checkFirewallRules(remoteAddress)
    }
}
```

### 问题8：消息序列化失败

**症状：**

```
cactor.serialization.SerializationException: Cannot serialize message
```

**解决方案：**

```cangjie
// 确保消息类可序列化
struct SerializableMessage : Serializable {
    let id: Int64
    let data: String
    let timestamp: Long

    // 自定义序列化
    func serialize(): ByteArray {
        let buffer = ByteBuffer.allocate(1024)
        buffer.putLong(id)
        buffer.putInt(data.length())
        buffer.put(data.getBytes())
        buffer.putLong(timestamp)
        return buffer.array()
    }

    static func deserialize(data: ByteArray): SerializableMessage {
        let buffer = ByteBuffer.wrap(data)
        let id = buffer.getLong()
        let dataLength = buffer.getInt()
        let messageData = ByteArray(dataLength)
        buffer.get(messageData)
        let timestamp = buffer.getLong()

        return SerializableMessage(
            id: id,
            data: String(messageData),
            timestamp: timestamp
        )
    }
}

// 序列化测试
class SerializationTester {
    func testSerialization(message: Message): Bool {
        try {
            let serializer = system.serialization().findSerializerFor(message)
            let bytes = serializer.serialize(message)
            let deserialized = serializer.deserialize(bytes, message.getClass())
            return message.equals(deserialized)
        } catch (e: SerializationException) {
            logger.error("Serialization test failed: ${e.message}")
            return false
        }
    }
}
```

## 集群问题

### 问题9：节点无法加入集群

**诊断步骤：**

```cangjie
class ClusterDiagnostics {
    func diagnoseClusterJoin(): Unit {
        let cluster = Cluster.get(system)

        // 1. 检查种子节点
        let seedNodes = cluster.getSeedNodes()
        logger.info("Seed nodes: ${seedNodes}")

        seedNodes.forEach { seedNode =>
            let connectivity = testConnectivity(seedNode.host, seedNode.port)
            if (!connectivity.success) {
                logger.error("Cannot connect to seed node: ${seedNode}")
            }
        }

        // 2. 检查集群配置
        let clusterConfig = system.getConfig().getConfig("cactor.cluster")
        logger.info("Cluster configuration: ${clusterConfig}")

        // 3. 检查网络分区
        checkNetworkPartition()

        // 4. 监听集群事件
        cluster.subscribe(self, ClusterEvent.class)
    }

    override func receive(message: Message): Unit {
        match (message) {
            case MemberUp(member) => {
                logger.info("Member joined: ${member}")
            }
            case MemberRemoved(member, previousStatus) => {
                logger.warn("Member removed: ${member}, previous status: ${previousStatus}")
            }
            case UnreachableMember(member) => {
                logger.error("Member unreachable: ${member}")
            }
        }
    }
}
```

## 调试工具

### 日志配置

```hocon
cactor {
  logging {
    level = "DEBUG"

    loggers = {
      "cactor.actor" = "DEBUG"
      "cactor.cluster" = "INFO"
      "cactor.remote" = "DEBUG"
      "cactor.serialization" = "WARN"
    }

    # 启用详细的Actor生命周期日志
    lifecycle-logging = true

    # 启用消息日志（仅用于调试）
    message-logging = false
  }
}
```

### 监控端点

```cangjie
class DiagnosticEndpoints {
    func setupHealthCheck(): Unit {
        let server = HttpServer.create(InetSocketAddress(8080), 0)

        // 健康检查端点
        server.createContext("/health") { exchange =>
            let health = checkSystemHealth()
            let response = health.toJson()

            exchange.getResponseHeaders().set("Content-Type", "application/json")
            exchange.sendResponseHeaders(200, response.length())
            exchange.getResponseBody().write(response.getBytes())
            exchange.close()
        }

        // 指标端点
        server.createContext("/metrics") { exchange =>
            let metrics = collectMetrics()
            let response = metrics.toPrometheusFormat()

            exchange.getResponseHeaders().set("Content-Type", "text/plain")
            exchange.sendResponseHeaders(200, response.length())
            exchange.getResponseBody().write(response.getBytes())
            exchange.close()
        }

        server.start()
    }

    func checkSystemHealth(): HealthStatus {
        let checks = [
            checkActorSystemHealth(),
            checkMemoryHealth(),
            checkClusterHealth(),
            checkDatabaseHealth()
        ]

        let overallHealth = checks.all { it.isHealthy }

        return HealthStatus(
            healthy: overallHealth,
            checks: checks,
            timestamp: System.currentTimeMillis()
        )
    }
}
```

## 故障排除清单

### 系统启动问题

- [ ] 检查配置文件语法
- [ ] 验证端口可用性
- [ ] 确认内存充足
- [ ] 检查文件权限
- [ ] 验证Java版本兼容性

### 性能问题

- [ ] 监控CPU使用率
- [ ] 检查内存使用情况
- [ ] 分析GC日志
- [ ] 监控消息队列长度
- [ ] 检查网络延迟

### 网络问题

- [ ] 测试网络连通性
- [ ] 检查防火墙规则
- [ ] 验证DNS解析
- [ ] 监控网络带宽
- [ ] 检查序列化配置

### 集群问题

- [ ] 验证种子节点配置
- [ ] 检查节点间网络连通性
- [ ] 监控集群事件
- [ ] 检查时钟同步
- [ ] 验证集群配置一致性

## 获取帮助

如果问题仍未解决，可以通过以下方式获取帮助：

- **社区论坛**: [https://community.cactor.dev](https://community.cactor.dev)
- **GitHub Issues**: [https://github.com/cactor/cactor/issues](https://github.com/cactor/cactor/issues)
- **官方文档**: [https://docs.cactor.dev](https://docs.cactor.dev)
- **技术支持**: support@cactor.dev

提交问题时，请包含：

- CActor版本信息
- 完整的错误日志
- 系统配置信息
- 重现问题的最小示例
- 环境信息（操作系统、Java版本等）
